
package com.chinacreator.c2etcd;


import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;

/**
 * @Author: jack.liang
 **/
public class EtcdClientFactory {

    private EtcdClientFactory() {
    }

    public static final EtcdClientFactory getInstance() {
        return SingletonHolder.INSTANCE;
    }

    private static class SingletonHolder {
        private static final EtcdClientFactory INSTANCE = new EtcdClientFactory();
    }

    private final ConcurrentMap<String /* key */, EtcdClient /* instance */> etcdClientMap = new ConcurrentHashMap<String, EtcdClient>();

    /**
     * <B>方法名称：</B>connect<BR>
     * <B>概要说明：</B>连接etcd<BR>
     * @Author: jack.liang
     * @Date: 2020/7/24 上午4:39
     * @param key					etcd主键
     * @param addresses				地址
     * @param usedHeartBeatLease	是否启用心跳
     * @param lazyInitialization	懒加载
     * @return EtcdClient
     */
    public EtcdClient connect(String key, String addresses, boolean usedHeartBeatLease, boolean lazyInitialization) {
        EtcdClient etcdClient = etcdClientMap.get(key);
        if (etcdClient == null) {
            etcdClient = new EtcdClientImpl(addresses, usedHeartBeatLease, lazyInitialization);
            etcdClientMap.putIfAbsent(key, etcdClient);
        }
        return etcdClient;
    }

    public EtcdClient getEtcdClient(String key) {
        return etcdClientMap.get(key);
    }

    public void removeEtcdClient(String key) throws InterruptedException, ExecutionException {
        EtcdClient etcdClient = etcdClientMap.get(key);
        if (etcdClient != null) {
            etcdClient.close();
            etcdClientMap.remove(key);
        }
    }
}
